package com.dianrui.operation.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;


import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class DeviceBindActivity extends BaseActivity {
    private String titles;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.car_name)
    EditText carName;
    @BindView(R.id.car_name_input)
    EditText carNameInput;


    @Override
    public int getContentViewId() {
        return R.layout.device_bind;
    }

    @Override
    public void initView() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle=getIntent().getExtras();
            if (bundle != null) {
                titles=bundle.getString("title");
                title.setText(titles);
            }
        }
    }

    @Override
    public void initData() {}


    @OnClick({R.id.back, R.id.bind, R.id.unbind,R.id.btn1,R.id.btn2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bind:
                if (StringUtils.isEmpty(carName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }

                if (StringUtils.isEmpty(carNameInput.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                    return;
                }
                startBind();
                break;
            case R.id.unbind:
                if (StringUtils.isEmpty(carName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_code_error));
                    return;
                }
                if (StringUtils.isEmpty(carNameInput.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_device_number_error));
                    return;
                }

                startUnBind();
                break;


            case R.id.btn1:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(DeviceBindActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                        intent.putExtra("camflag","4");
                        startActivityForResult(intent,104);
                    } else {
                        ActivityCompat.requestPermissions(DeviceBindActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                }else {
                    Intent intent=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag","4");
                    startActivityForResult(intent,104);
                }
                break;

            case R.id.btn2:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(DeviceBindActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent2=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                        intent2.putExtra("camflag","5");
                        startActivityForResult(intent2,105);
                    } else {
                        ActivityCompat.requestPermissions(DeviceBindActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                }else {
                    Intent intent2=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                    intent2.putExtra("camflag","5");
                    startActivityForResult(intent2,105);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 104:
                String imel=data.getStringExtra("IMEI");
                carName.setText(imel);
                break;

            case 105:
                String imel1=data.getStringExtra("IMEI");
                carNameInput.setText(imel1);
                break;
                default:
                    break;
        }
    }

    private void startBind() {
        showLoadingDialog("正在绑定中,请稍候...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("device", carName.getText().toString());//盒子号
        jsonObject.addProperty("number", carNameInput.getText().toString());//设备号
        jsonObject.addProperty("is_remove", "0");
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl()+Url.DEVICE_BIND, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null!=jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                spUtils.clear();
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void startUnBind() {
        showLoadingDialog("正在解绑,请稍候...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("device", carName.getText().toString());
        jsonObject.addProperty("number", carNameInput.getText().toString());
        jsonObject.addProperty("is_remove", "1");//是否解除：1解除，0否
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl()+Url.DEVICE_BIND, jsonObject.toString(),  new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {

                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null!=jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                spUtils.clear();
                                SharedUtil.setToken("");
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag","1");
                    startActivityForResult(intent,102);
                }
                break;

            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent=new Intent(DeviceBindActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag","2");
                    startActivityForResult(intent,103);
                }
                break;

            default:
                break;

        }

    }
}
